package com.library.system.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.library.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;

/**
 * 元数据处理
 *
 * @author hb
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Timestamp time=new Timestamp(System.currentTimeMillis());
        if(metaObject.hasSetter("createId") && metaObject.getValue("createId") == null) {
            this.setFieldValByName("createId", SecurityUtils.getUserId(),metaObject);
        }
        if(metaObject.hasSetter("createBy") && metaObject.getValue("createBy") == null) {
            this.setFieldValByName("createBy", SecurityUtils.getUsername(),metaObject);
        }
        if(metaObject.hasSetter("createTime") && metaObject.getValue("createTime") == null) {
            this.setFieldValByName("createTime", time, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Timestamp time=new Timestamp(System.currentTimeMillis());
        if(metaObject.hasSetter("updateId") && metaObject.getValue("updateId") == null) {
            this.setFieldValByName("updateId", SecurityUtils.getUserId(),metaObject);
        }
        if(metaObject.hasSetter("updateBy") && metaObject.getValue("updateBy") == null) {
            this.setFieldValByName("updateBy", SecurityUtils.getUsername(),metaObject);
        }
        if(metaObject.hasSetter("updateTime") && metaObject.getValue("updateTime") == null) {
            this.setFieldValByName("updateTime", time, metaObject);
        }
    }
}
